package com.zhixianggou.caibaobox.lottery.dataCollect;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zhixianggou.caibaobox.lottery.dataCollect.cover.SLotteryCover;
import com.zhixianggou.caibaobox.lottery.dataCollect.cover.WLotteryCover;
import com.zhixianggou.caibaobox.lottery.dataCollect.dao.*;
import com.zhixianggou.caibaobox.lottery.dataCollect.dto.SLotteryDto;
import com.zhixianggou.caibaobox.lottery.dataCollect.dto.SLotteryPageDto;
import com.zhixianggou.caibaobox.lottery.dataCollect.dto.WLotteryDto;
import com.zhixianggou.caibaobox.lottery.dataCollect.dto.WLotteryPageDto;
import com.zhixianggou.caibaobox.lottery.dataCollect.entities.*;
import com.zhixianggou.caibaobox.lottery.dataCollect.utils.CookieUtil;
import com.zhixianggou.caibaobox.lottery.dataCollect.utils.DataCollectUtil;
import com.zhixianggou.caibaobox.lottery.dataCollect.utils.UserAgentUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zyq
 * 8/22/24 12:08 PM
 */
@Component
public class WelfareLotteryCollectService {

   @Resource
   RestTemplate restTemplate;


   @Resource
   WSsqMapper wSsqMapper;

   @Resource
   WKl8Mapper wKl8Mapper;

   @Resource
   W3dMapper w3dMapper;

   @Resource
   WQlcMapper wQlcMapper;



   /**
    * 收集数据--福彩双色球
    */
   public void getData4SSQ(HttpHeaders headers) throws InterruptedException {
      //获取db中的最大期数
      WSsq wSsq = wSsqMapper.selectMaxCode();
      String issueStart = wSsq == null ? null : wSsq.getCode();
      String issueEnd = null;
      Integer total = 0;

//      HttpHeaders headers = new HttpHeaders();
//      String userAgent = UserAgentUtil.randomUserAgent();
//      headers.set("cookie", CookieUtil.getCookie("https://www.cwl.gov.cn",userAgent));
//      headers.set("user-agent", userAgent);
      TimeUnit.SECONDS.sleep(3);

      //获取网站最近一期数据
      ResponseEntity<String> responseEntity = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_SSQ.getName(), 1, 1);
      WLotteryPageDto lastDataPageDto = JSON.parseObject(responseEntity.getBody(), WLotteryPageDto.class);
      if(lastDataPageDto == null || CollectionUtils.isEmpty(lastDataPageDto.getResult())){
         return;
      }
      issueEnd = lastDataPageDto.getResult().get(0).getCode();
      if(StringUtils.isNotBlank(issueStart) && StringUtils.isNotBlank(issueEnd)){
         ResponseEntity<String> responseEntityFirst = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_SSQ.getName(), 1, 1, issueStart, issueEnd);
         WLotteryPageDto firstPageDto = JSON.parseObject(responseEntityFirst.getBody(), WLotteryPageDto.class);
         total = firstPageDto.getTotal();
      }else{
         total = lastDataPageDto.getTotal();
      }


      int pageSize = 30;
      //由于网站数据查询结果是倒序列表，我们需要从最后页开始往前查询
      //根据总条数和每页条数计算总页数
      int pageNo = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);

      List<WSsq> importList = new ArrayList<>();
      while (pageNo > 0) {
         ResponseEntity<String> responseEntityAll = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_SSQ.getName(), pageNo, pageSize, issueStart, issueEnd);
         WLotteryPageDto pageDto = JSON.parseObject(responseEntityAll.getBody(), WLotteryPageDto.class);
         List<WLotteryDto> result = pageDto.getResult();
         List<WSsq> poList = WLotteryCover.INSTANCE.toSSQPo(result);
         if(issueStart == null){
            importList.addAll(poList);
         }else {
            importList.addAll(poList.stream().filter(po -> Integer.valueOf(po.getCode()) > Integer.valueOf(issueStart)).collect(Collectors.toList()));
         }
         if(CollectionUtils.isEmpty(importList)){
            break;
         }
         //正序排序后导入数据库
         wSsqMapper.insertBatch(importList.stream().sorted(Comparator.comparing(WSsq::getCodeInt)).collect(Collectors.toList()));
         pageNo --;
         importList.clear();
         TimeUnit.SECONDS.sleep(5);
      }
      System.out.println("福彩双色球数据导入完成");
   }


   /**
    * 收集数据--福彩3D
    */
   public void getData43d(HttpHeaders headers) throws InterruptedException {
      //获取db中的最大期数
      W3d w3d = w3dMapper.selectMaxCode();
      String issueStart = w3d == null ? null : w3d.getCode();
      String issueEnd = null;
      Integer total = 0;

//      HttpHeaders headers = new HttpHeaders();
//      String userAgent = UserAgentUtil.randomUserAgent();
//      headers.set("cookie", CookieUtil.getCookie("https://www.cwl.gov.cn",userAgent));
//      headers.set("user-agent", userAgent);
      TimeUnit.SECONDS.sleep(3);

      //获取网站最近一期数据
      ResponseEntity<String> responseEntity = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_3D.getName(), 1, 1);
      WLotteryPageDto lastDataPageDto = JSON.parseObject(responseEntity.getBody(), WLotteryPageDto.class);
      if(lastDataPageDto == null || CollectionUtils.isEmpty(lastDataPageDto.getResult())){
         return;
      }
      issueEnd = lastDataPageDto.getResult().get(0).getCode();
      if(StringUtils.isNotBlank(issueStart) && StringUtils.isNotBlank(issueEnd)){
         ResponseEntity<String> responseEntityFirst = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_3D.getName(), 1, 1, issueStart, issueEnd);
         WLotteryPageDto firstPageDto = JSON.parseObject(responseEntityFirst.getBody(), WLotteryPageDto.class);
         total = firstPageDto.getTotal();
      }else{
         total = lastDataPageDto.getTotal();
      }

      int pageSize = 30;
      //由于网站数据查询结果是倒序列表，我们需要从最后页开始往前查询
      //根据总条数和每页条数计算总页数
      int pageNo = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);

      List<W3d> importList = new ArrayList<>();
      while (pageNo > 0) {
         WLotteryPageDto pageDto = null;
         try{
            ResponseEntity<String> responseEntityAll = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_3D.getName(), pageNo, pageSize, issueStart, issueEnd);
            pageDto = JSON.parseObject(responseEntityAll.getBody(), WLotteryPageDto.class);
         }catch (Exception e){
            pageNo --;
            continue;
         }

         List<WLotteryDto> result = pageDto.getResult();
         List<W3d> poList = WLotteryCover.INSTANCE.to3dPo(result);
         if(issueStart == null){
            importList.addAll(poList);
         }else {
            importList.addAll(poList.stream().filter(po -> Integer.valueOf(po.getCode()) > Integer.valueOf(issueStart)).collect(Collectors.toList()));
         }
         if(CollectionUtils.isEmpty(importList)){
            break;
         }
         //正序排序后导入数据库
         w3dMapper.insertBatch(importList.stream().sorted(Comparator.comparing(W3d::getCodeInt)).collect(Collectors.toList()));
         pageNo --;
         importList.clear();
         TimeUnit.SECONDS.sleep(5);
      }
      System.out.println("福彩3D数据导入完成");
   }


   /**
    * 收集数据--福彩KL8
    */
   public void getData4kl8(HttpHeaders headers) throws InterruptedException {
      //获取db中的最大期数
      WKl8 wkl8 = wKl8Mapper.selectMaxCode();
      String issueStart = wkl8 == null ? null : wkl8.getCode();
      String issueEnd = null;
      Integer total = 0;


      TimeUnit.SECONDS.sleep(3);

      //获取网站最近一期数据
      ResponseEntity<String> responseEntity = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_KL8.getName(), 1, 1);
      WLotteryPageDto lastDataPageDto = JSON.parseObject(responseEntity.getBody(), WLotteryPageDto.class);
      if(lastDataPageDto == null || CollectionUtils.isEmpty(lastDataPageDto.getResult())){
         return;
      }
      issueEnd = lastDataPageDto.getResult().get(0).getCode();
      if(StringUtils.isNotBlank(issueStart) && StringUtils.isNotBlank(issueEnd)){
         ResponseEntity<String> responseEntityFirst = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_KL8.getName(), 1, 1, issueStart, issueEnd);
         WLotteryPageDto firstPageDto = JSON.parseObject(responseEntityFirst.getBody(), WLotteryPageDto.class);
         total = firstPageDto.getTotal();
      }else{
         total = lastDataPageDto.getTotal();
      }

      int pageSize = 30;
      //由于网站数据查询结果是倒序列表，我们需要从最后页开始往前查询
      //根据总条数和每页条数计算总页数
      int pageNo = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);

      List<WKl8> importList = new ArrayList<>();
      while (pageNo > 0) {
         WLotteryPageDto pageDto = null;
         try{
            ResponseEntity<String> responseEntityAll = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_KL8.getName(), pageNo, pageSize, issueStart, issueEnd);
            pageDto = JSON.parseObject(responseEntityAll.getBody(), WLotteryPageDto.class);
         }catch (Exception e){
            pageNo --;
            continue;
         }

         List<WLotteryDto> result = pageDto.getResult();
         List<WKl8> poList = WLotteryCover.INSTANCE.toKL8Po(result);
         if(issueStart == null){
            importList.addAll(poList);
         }else {
            importList.addAll(poList.stream().filter(po -> Integer.valueOf(po.getCode()) > Integer.valueOf(issueStart)).collect(Collectors.toList()));
         }
         if(CollectionUtils.isEmpty(importList)){
            break;
         }
         //正序排序后导入数据库
         wKl8Mapper.insertBatch(importList.stream().sorted(Comparator.comparing(WKl8::getCodeInt)).collect(Collectors.toList()));
         pageNo --;
         importList.clear();
         TimeUnit.SECONDS.sleep(5);
      }
      System.out.println("福彩KL8数据导入完成");
   }



   /**
    * 收集数据--福彩QLC
    */
   public void getData4QLC(HttpHeaders headers) throws InterruptedException {
      //获取db中的最大期数
      WQlc wQlc = wQlcMapper.selectMaxCode();
      String issueStart = wQlc == null ? null : wQlc.getCode();
      String issueEnd = null;
      Integer total = 0;

//      HttpHeaders headers = new HttpHeaders();
//      String userAgent = UserAgentUtil.randomUserAgent();
//      headers.set("cookie", CookieUtil.getCookie("https://www.cwl.gov.cn",userAgent));
//      headers.set("user-agent", userAgent);
      TimeUnit.SECONDS.sleep(3);

      //获取网站最近一期数据
      ResponseEntity<String> responseEntity = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_QLC.getName(), 1, 1);
      WLotteryPageDto lastDataPageDto = JSON.parseObject(responseEntity.getBody(), WLotteryPageDto.class);
      if(lastDataPageDto == null || CollectionUtils.isEmpty(lastDataPageDto.getResult())){
         return;
      }
      issueEnd = lastDataPageDto.getResult().get(0).getCode();
      if(StringUtils.isNotBlank(issueStart) && StringUtils.isNotBlank(issueEnd)){
         ResponseEntity<String> responseEntityFirst = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_QLC.getName(), 1, 1, issueStart, issueEnd);
         WLotteryPageDto firstPageDto = JSON.parseObject(responseEntityFirst.getBody(), WLotteryPageDto.class);
         total = firstPageDto.getTotal();
      }else{
         total = lastDataPageDto.getTotal();
      }

      int pageSize = 30;
      //由于网站数据查询结果是倒序列表，我们需要从最后页开始往前查询
      //根据总条数和每页条数计算总页数
      int pageNo = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);

      List<WQlc> importList = new ArrayList<>();
      while (pageNo > 0) {
         WLotteryPageDto pageDto = null;
         try{
            ResponseEntity<String> responseEntityAll = DataCollectUtil.getList4WLottery(restTemplate, headers, DataCollectUtil.WName.W_QLC.getName(), pageNo, pageSize, issueStart, issueEnd);
            pageDto = JSON.parseObject(responseEntityAll.getBody(), WLotteryPageDto.class);
         }catch (Exception e){
            pageNo --;
            continue;
         }

         List<WLotteryDto> result = pageDto.getResult();
         List<WQlc> poList = WLotteryCover.INSTANCE.toWQlcPo(result);
         if(issueStart == null){
            importList.addAll(poList);
         }else {
            importList.addAll(poList.stream().filter(po -> Integer.valueOf(po.getCode()) > Integer.valueOf(issueStart)).collect(Collectors.toList()));
         }
         if(CollectionUtils.isEmpty(importList)){
            break;
         }
         //正序排序后导入数据库
         wQlcMapper.insertBatch(importList.stream().sorted(Comparator.comparing(WQlc::getCodeInt)).collect(Collectors.toList()));
         pageNo --;
         importList.clear();
         TimeUnit.SECONDS.sleep(5);
      }
      System.out.println("福彩QLC数据导入完成");
   }


   public static void main(String[] args) {
      WLotteryDto dto = new WLotteryDto();

      dto.setCode("2020090");
      dto.setDate("2020-08-23(星期五)");
      WSsq ssqPo = WLotteryCover.INSTANCE.toSSQPo(dto);
      System.out.println(ssqPo);
   }

}
